import { onMounted } from 'vue';

/**
 * Vue onMounted 周期函数封装
 */
export class VueMountedCycle {
    callbackList: Array<() => void>;

    constructor() {
        this.callbackList = [];
    }

    push(cb: () => void): void {
        this.callbackList.push(cb);
    }

    trigger(): void {
        onMounted(() => {
            this.callbackList.forEach(cb => cb());
        });
    }
}

/**
 * 检查视频是否可播放
 */
export function checkVideoCanPlay(src: string): Promise<boolean> {
    return new Promise(resolve => {
        const WIDTH = 10;
        const HEIGHT = 10;

        const canvasEl = document.createElement('canvas');
        canvasEl.width = WIDTH;
        canvasEl.height = HEIGHT;

        const context = canvasEl.getContext('2d');

        if (context) {
            const videoEl = document.createElement('video');
            videoEl.width = WIDTH;
            videoEl.height = HEIGHT;
            videoEl.muted = true;

            videoEl.addEventListener('loadedmetadata', function () {
                this.currentTime = 3000;
            });

            videoEl.addEventListener('timeupdate', function () {
                context.drawImage(videoEl, 0, 0);
                const frame = context.getImageData(0, 0, WIDTH, HEIGHT);
                if (frame.data.every(d => d === 0)) {
                    resolve(false);
                } else {
                    resolve(true);
                }
            });

            videoEl.src = src;

            // ...
        } else {
            resolve(false);
        }
    });
}
